<?php
$action = $_POST['action'];
$table = $_POST['table'];

mysql_connect("localhost", "orsino", "szapo123") or die(mysql_error());
mysql_select_db("konferencje") or die(mysql_error());

switch ($action) {
	case"getdata":
		$fields = $_POST['fields'];
		$fe = json_decode($fields);
		$primary_key = $_POST['pk'];
		$page = $_POST['page'];
		$order_col = $_POST['order_col'];
		$order_dir = $_POST['order_dir'];
		$offset = $page * $_POST['limit'];

		$row_count = mysql_query("SELECT * FROM ".$table);
		$count = mysql_num_rows($row_count);

		$qColumnNames = mysql_query("SHOW COLUMNS FROM ".$table);
		$numColumns = mysql_num_rows($qColumnNames);
		$x = 0;
		while ($x < $numColumns) {
			$colname = mysql_fetch_row($qColumnNames);
			$column_names[$colname[0]] = $colname[0];
			$x++;
		}
		$olds = array();
		$news = array();
		for($i=0;$i<count($fe);$i++){
			$olds[] = $fe[$i]->old;
			$news[$fe[$i]->old] = $fe[$i]->my;
			$olds2[$fe[$i]->my] = $fe[$i]->old;
		}

		$temp = array_merge($column_names,$olds2);

		$columns = array();
		foreach($news as $k=>$v){
			if(in_array($k,$column_names)){
				$columns[$k] = $v;
				unset($column_names[$v]);
			}
		}
		foreach ($column_names as $c) {
			if(!in_array($c,$olds))
				$columns[$c] = $c;
		}

		foreach($columns as $k=>$v){
			if($v == 'none')
				unset($columns[$k]);
		}
//		echo "<pre>",print_r($columns),"</pre>";exit;
		$sql = "SELECT * FROM ".$table." order by " . $order_col . " " . $order_dir . " limit " . $_POST['limit'] . " offset " . $offset . "";
		$result = mysql_query($sql)
				or die(mysql_error());
		$i = 0;
		$output = array();
		while ($row = mysql_fetch_array($result)) {
			$output[$i]['Lp.'] = $i + $offset + 1;

			foreach ($columns as $v=>$k) {
				if($k == $primary_key)
					$output[$i]['pk'] = $row[$v];
				else
					$output[$i][$k] = $row[$v];
			}
			$i++;
		}
//		echo "<pre>",print_r($output),"</pre>";exit;
		$data = array('count' => $count,'cols_names'=>$temp, 'data' => $output);
		echo json_encode($data);
		break;
		case"updatedata":
			$id = $_POST['id'];
			$value = $_POST['value'];
			$pk = $_POST['pk'];
			$parts = explode('_|_',$id);
			$id_record = trim($parts[0]);
			$field = trim($parts[1]);
//			echo $id. " - " . $value;
			$sql = 'UPDATE '. $table .' SET `' . $field . "`='" . $value . "' WHERE " . $pk . "=" .$id_record;
			if(mysql_query($sql)){
				echo 1;
			}else{
				echo 0;
				die();
			}
		break;
}
?>
